/*************************************************
 * ThinkJot V2
 * Author: Jeswin P. (jeswin@process64.com)
 * Website: http://www.process64.com/thinkjot/
 * This code is distributed under the terms of the
 * Apache License, Version 2.0.
 * **********************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Xsl;

using ThinkJot.Core.Utils;

namespace ThinkJot.Core.Blogs.Providers.Xml
{
    public class XmlBlogRollDP : BlogRollDP
    {
        public override string GetFormattedBlogRollContent(string blogName)
        {
            try
            {
                // Load up the OPML
                string opmlPath = Path.Combine(ProviderSettings.GetBlogContentFolder(blogName), "blogroll.opml");
                string xsltPath = Path.Combine(ProviderSettings.GetBlogContentFolder(blogName), "opml.xslt");

                XmlTextReader opmlReader = new XmlTextReader(opmlPath);
                XslCompiledTransform xmlTransform = new XslCompiledTransform();

                // Load up the XSLT
                xmlTransform.Load(xsltPath);

                // Transform
                StringBuilder sb = new StringBuilder();
                XmlWriter writer = XmlWriter.Create(sb, xmlTransform.OutputSettings);
                xmlTransform.Transform(opmlReader, writer);
                string transformed = sb.ToString();
                opmlReader.Close();
                writer.Close();
                return transformed;
            }
            catch (Exception ex)
            {
                new XmlLogger().LogException(ex, blogName);
                return "Error:BlogRoll";
            }
        }

        public override BlogRoll GetBlogRoll(string blogName)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Path.Combine(ProviderSettings.GetBlogContentFolder(blogName), "blogroll.opml"));
                XmlNode body = doc.SelectSingleNode("//body");

                BlogRoll roll = new BlogRoll();
                BlogRollEntry entry;
                foreach (XmlNode node in body.ChildNodes)
                {
                    if (node.Name == "outline")
                    {
                        entry = new BlogRollEntry(node);
                        roll.Entries.Add(entry);
                    }
                }
                return roll;
            }
            catch (Exception ex)
            {
                new XmlLogger().LogException(ex, blogName);
                return new BlogRoll();
            }
        }
    }
}
